package com.gong.yuanma.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author GongChang
 * @version 1.0
 * @date 2021/6/20 0020 20:33
 */

class Data{
    private int i = 0;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void push(){
        lock.lock();
        try {
            while (i != 0){
                condition.await();
            }
            i++;
            System.out.println(Thread.currentThread().getName()+"   1");
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void get(){
        lock.lock();
        try {
            while (i == 0){
                condition.await();
            }
            i--;
            System.out.println(Thread.currentThread().getName()+"   0");
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

public class ProduceConsumer {
    public static void main(String[] args) {
        Data data = new Data();

        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                data.push();
            }
        },"aa").start();

        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                data.push();
            }
        },"cc").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data.get();
            }
        },"bb").start();
    }
}
